//
// Created by mi on 2024/5/6.
//
#include <thread>
#include <iostream>
#include <future>

int fun (int i) {
    std::cout << "I'm fun" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(3));
    return i;
}
// 异步线程，等待线程结束，取到结果
int main () {
    std::jthread t(fun, 1);
    t.join();

    std::future<int> fe = std::async(std::launch::async, fun, 1);
    std::future_status status;
    do {
        status = fe.wait_for(std::chrono::seconds(1));
        // 异步操作还没有开始
        if (status == std::future_status::deferred) {
            std::cout << "deferred\n";
        } else if (status == std::future_status::timeout) {
            std::cout << "timeout\n";
        } else if (status == std::future_status::ready) {
            std::cout << "ready!\n";
        }
    } while (status != std::future_status::ready);
    std::cout << "result is " << fe.get() << '\n';
    return 0;
}